package com.zhanghe.im.handler;

import com.zhanghe.im.request.LoginRequestPacket;
import com.zhanghe.im.response.LoginResponsePacket;
import com.zhanghe.im.session.Session;
import com.zhanghe.im.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
import java.util.UUID;

/**
 * SimpleLoginResponseHandler
 *
 * @author Clevo
 * @date 2018/10/23
 */
public class SimpleLoginResponseHandler extends SimpleChannelInboundHandler<LoginResponsePacket> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(UUID.randomUUID().toString());
        loginRequestPacket.setUserName("zhanghe");
        loginRequestPacket.setPassword("123456");
//        ctx.channel().writeAndFlush(loginRequestPacket);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginResponsePacket loginResponsePacket) throws Exception {
        if(loginResponsePacket.getSuccess()){
            Session session = new Session();
            session.setUserId(loginResponsePacket.getUserId());
            session.setUserName(loginResponsePacket.getUserName());
            SessionUtil.bindSession(session,channelHandlerContext.channel());
            System.out.println(new Date() + ": 客户端登录成功");
        } else {
            System.out.println(new Date() + ": 客户端登录失败，原因：" + loginResponsePacket.getReason());
        }
    }
}
